package com.xywh.wanandroid.viewmodel

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.xywh.wanandroid.data.model.bean.ArticleItem
import com.xywh.wanandroid.data.repository.WanAndroidRepository
import com.xywh.wanandroid.ext.requestCompose
import com.xywh.wanandroid.ext.showToastMsg
import com.xywh.wanandroid.network.apiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import javax.inject.Inject

@HiltViewModel
class SearchComposeViewModel @Inject constructor(
    val repository: WanAndroidRepository
) : BaseViewModel() {

    var articleList: MutableState<Flow<PagingData<ArticleItem>>?> = mutableStateOf(null)

    fun queryBySearchKey(key: String) {
        articleList.value = repository.fetchSearchDataList(key).cachedIn(viewModelScope)
    }


    /**
     * 添加收藏
     * @param id Int
     */
    fun addCollectArticle(id: Int, updateMainScreenCollectListData: () -> Unit) {
        requestCompose(
            { apiService.addCollectArticle(id) },
            {
                updateMainScreenCollectListData.invoke()
                showToastMsg("收藏成功")
            }, {
                showToastMsg(it.errorMsg)
            },
            true,
            "收藏中..."
        )
    }

    /**
     * 取消收藏
     * @param id Int
     */
    fun cancelCollectArticle(id: Int, updateMainScreenCollectListData: () -> Unit) {
        requestCompose(
            { apiService.cancelCollectArticle(id) },
            {
                updateMainScreenCollectListData.invoke()
                showToastMsg("取消收藏成功")
            }, {
                showToastMsg(it.errorMsg)
            },
            true,
            "取消收藏中..."
        )
    }
}